package edu.example.Absence.servlet;

import edu.example.Absence.Dao.absenceDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

@WebServlet("/absenceAdd2")
public class AbsenceAddServlet2 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         String time =req.getParameter("date");
         System.out.println(time);
        SimpleDateFormat sbd = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = sbd.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(parse);
        System.out.println(time);
        int id = Integer.parseInt(req.getParameter("userId"));
        String name=req.getParameter("name");
        String gender = req.getParameter("gender");
        String building = req.getParameter("building");
        String room =req.getParameter("room");
        /*Long aLong = Long.valueOf(time);
        System.out.println(aLong);*/
        // 将日期字符串转换为 LocalDate 对象
        LocalDate date = LocalDate.parse(time);
        // 将 LocalDate 转换为 Instant 对象（使用系统默认时区）
        Instant instant = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
        // 获取时间戳（毫秒）
        long timestamp = instant.toEpochMilli();
        int affectrows = new absenceDao().absenceAdd(timestamp,id,name,gender,building,room);
        if ( affectrows > 0) {
            resp.getWriter().println("<script> location.href='absence'</script>");
        } else {
            // 处理失败的情况
            resp.getWriter().println("<script>alert('添加失败'); location.href='absence'</script>");
        }
    }
}
